package cn.yujiago.shiro.controller;

import cn.yujiago.shiro.domain.UserDO;
import cn.yujiago.shiro.pojo.LayuiTableResult;
import cn.yujiago.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session){

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        Subject subject = SecurityUtils.getSubject();

        try {
            System.out.println("-------------login------------");
            subject.login(token);
//            subject.getSession().setAttribute("curentUser", username);
            session.setAttribute("currentUser", username);
            return "redirect:/page/common/index";
        } catch (AuthenticationException e) {
            System.out.println("认证失败！");
            return "redirect:/page/anon/login";
        }

    }

    @RequestMapping("/user/getUserByDeptId")
    @ResponseBody
    public LayuiTableResult<UserDO> getUserByDeptId(@RequestParam(value = "deptId", defaultValue = "0") Long deptId, @RequestParam("page") int page, @RequestParam("limit") int limit){
        return userService.getUserByDeptId(deptId, page, limit);
    }
}
